package cn.itcast.jdbctemplate;

import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

public class JdbcTemplateDemo2 {

    //获取JdbcTemplate对象
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /*
        修改1号数据的 salary 为 10000
     */
    @Test
    public void test1(){
        //定义SQL
        String sql = "update emp set salary = 10000 where id = 6";
        //执行SQL
        int count = template.update(sql);
        System.out.println(count);
    }

    /*
        添加一条数据
     */
    @Test
    public void test2(){
        //定义SQL
        String sql = "insert into emp(id,name,gender,salary) values(?,?,?,?)";
        //执行SQL
        int count = template.update(sql, 12,"郭靖", "男", 5000);
        System.out.println(count);
    }

    /*
        删除一条数据
     */
    @Test
    public void test3(){
        //定义SQL
        String sql = "delete from emp where id = ?";
        //执行SQL
        int count = template.update(sql,12);
        System.out.println(count);
    }

    /*
        查询 id 是 6 的记录,将其封装为 Map 集合
        注意: 这个方法查询的长度只能是1
     */
    @Test
    public void test4(){
        //定义SQL
        String sql = "select * from emp where id = ?";
        //执行SQL
        Map<String, Object> map = template.queryForMap(sql,6);
        System.out.println(map);
    }

    /*
        查询所有记录,将其封装为List
     */
    @Test
    public void test5(){
        //定义SQL
        String sql = "select * from emp";
        //执行SQL
        List<Map<String, Object>> list = template.queryForList(sql);
        for (Map<String, Object> stringObject : list) {
            System.out.println(stringObject);
        }
    }

    /*
        查询所有记录,将其封装为 Emp 对象的 Lest 集合
     */
    @Test
    public void test6(){
        //定义SQL
        String sql = "select * from emp";
        //执行SQL
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /*
        查询总记录数
     */
    @Test
    public void test7(){
        //定义SQL
        String sql = "select count(id) from emp";
        //执行SQL
        Long totel = template.queryForObject(sql, Long.class);
        System.out.println(totel);
    }

}
